<template>
	<div class="pager-container" v-show="pageNumber > 1">
		<a @click.prevent="handleClick(1)" :class="{ disabled: current === 1 }">|&lt;&lt;</a>
		<a @click.prevent="handleClick(current - 1)" :class="{ disabled: current === 1 }">&lt;&lt;</a>
		<a
			@click.prevent="handleClick(n)"
			v-for="(n, index) in numbers"
			:key="index"
			:class="{ active: n === current }"
			>{{ n }}</a
		>
		<a @click.prevent="handleClick(current + 1)" :class="{ disabled: current === pageNumber }">&gt;&gt;</a>
		<a @click.prevent="handleClick(pageNumber)" :class="{ disabled: current === pageNumber }">&gt;&gt;|</a>
	</div>
</template>

<script>
export default {
	name: 'Pager',
	emits: ['pageChange'],
	props: {
		current: { type: Number, default: 1 },
		total: { type: Number, default: 0 },
		limit: { type: Number, default: 10 },
		visibleNumber: { type: Number, default: 10 },
	},
	methods: {
		handleClick(newPage) {
			if (newPage < 1) {
				newPage = 1
			}
			if (newPage > this.pageNumber) {
				newPage = this.pageNumber
			}
			if (newPage === this.current) {
				return
			}
			this.$emit('pageChange', newPage)
		},
	},
	computed: {
		pageNumber() {
			return Math.ceil(this.total / this.limit)
		},
		visibleMin() {
			// 得到显示的最小数字
			let min = this.current - Math.floor(this.visibleNumber / 2)
			if (min < 1) {
				min = 1
			}
			return min
		},
		visibleMax() {
			let max = this.visibleMin + this.visibleNumber - 1
			if (max > this.pageNumber) {
				max = this.pageNumber
			}
			return max
		},
		numbers() {
			return Array.from(
				{ length: this.visibleMax - this.visibleMin + 1 },
				(val, index) => this.visibleMin + index
			)
		},
	},
}
</script>

<style lang="less" scoped>
@import '~@/styles/basic/var.less';
.pager-container {
	display: flex;
	justify-content: center;
	margin: 20px 0;
	a {
		color: @primary;
		cursor: pointer;
		margin: 0 5px;
		padding: 0 1px;

		&.disabled {
			color: @lightWords;
			cursor: not-allowed;
		}
		&.active {
			color: @words;
			font-weight: 700;
			cursor: text;
		}
	}
}
</style>
